import Vue from 'vue';

/* eslint-disable */
/** 判断微信环境 */
function inWeiXin() {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true
    } else {
        return false
    }
}

/**
 * 判断安卓或者苹果
 * return String 'Android' ,'IOS' ,'PC系统'
 * */
function phoneType() {
    var u = navigator.userAgent
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
    if (isAndroid) {
        return 'Android'
    } else if (isiOS) {
        return 'IOS'
    } else {
        return 'PC'
    }
}

/** 动态添加meta */
function setMeta() {
    if (!document.querySelector('meta[content="upgrade-insecure-requests"]')) {
        var oMeta = document.createElement('meta')
        oMeta.setAttribute('http-equiv', 'Content-Security-Policy')
        oMeta.setAttribute('content', 'upgrade-insecure-requests')
        document.getElementsByTagName('head')[0].appendChild(oMeta)
    }
}

/** 环境判断 */
function environment() {
    var devCondition = window.top.location.href.search(/test/) > -1
    var localCondition = window.top.location.href.indexOf('localhost') > -1
    if (!devCondition && !localCondition) {
        return true
    } else {
        return false
    }
}

// 设置手机app环境适配
function adaptive() {
    (function (doc, win) {
        // 分辨率适配Resolution Adaptive
        var docEl = doc.documentElement,
            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
            recalc = function () {
                var clientWidth = docEl.clientWidth
                if (!clientWidth) return
                docEl.style.fontSize = 100 * (clientWidth / 750) + 'px'
            }
        // console.log("设置html的font-size")
        // Abort if browser does not support addEventListener
        if (!doc.addEventListener) return
        win.addEventListener(resizeEvt, recalc, false)
        doc.addEventListener('DOMContentLoaded', recalc, false);

        // 一物理像素在不同屏幕的显示效果不一样。要根据devicePixelRatio来修改meta标签的scale,要注释上面的meta标签
        (function () {
            return
            var dpr = scale = 1
            var isIPhone = win.navigator.appVersion.match(/iphone/gi)
            var devicePixelRatio = win.devicePixelRatio
            if (isIPhone) {
                // iOS下，对于2和3的屏，用2倍的方案，其余的用1倍方案
                if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
                    dpr = 3
                } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)) {
                    dpr = 2
                } else {
                    dpr = 1
                }
            } else {
                // 其他设备下，仍旧使用1倍的方案
                dpr = 1
            }
            scale = 1 / dpr

            //
            var metaEl = ''
            metaEl = doc.createElement('meta')
            metaEl.setAttribute('name', 'viewport')
            metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no')
            if (docEl.firstElementChild) {
                docEl.firstElementChild.appendChild(metaEl)
            } else {
                var wrap = doc.createElement('div')
                wrap.appendChild(metaEl)
                doc.write(wrap.innerHTML)
            }
        })()
    })(document, window)
}

// 设置官网环境适配
function websiteAdaptive() {
    var userAgentInfo = navigator.userAgent
    var Agents = ['Android', 'iPhone',
        'SymbianOS', 'Windows Phone',
        'iPad', 'iPod']
    var flag = true
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false
            break
        }
    }
    if (flag) {
        var winWidth = document.documentElement.offsetWidth ||

            document.body.offsetWidth

        winWidth = winWidth < 1366 ? 1366 : winWidth

        var oHtml = document.getElementsByTagName('html')[0]

        oHtml.style.fontSize = 100 * winWidth / 1920 + 'px'

        window.addEventListener('resize', function () {
            var winWidth = document.documentElement.offsetWidth || document.body.offsetWidth

            winWidth = winWidth < 1400 ? 1400 : winWidth

            var oHtml = document.getElementsByTagName('html')[0]

            oHtml.style.fontSize = 100 * winWidth / 1920 + 'px'
        })
    } else {
        (function (doc, win) {
            // 分辨率适配Resolution Adaptive
            var docEl = doc.documentElement,
                resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
                recalc = function () {
                    var clientWidth = docEl.clientWidth
                    // console.log(clientWidth)
                    if (!clientWidth) return
                    docEl.style.fontSize = 100 * (clientWidth / 750) + 'px'
                }
            // console.log("设置html的font-size")
            // Abort if browser does not support addEventListener
            if (!doc.addEventListener) return
            win.addEventListener(resizeEvt, recalc, false)
            doc.addEventListener('DOMContentLoaded', recalc, false);

            // 一物理像素在不同屏幕的显示效果不一样。要根据devicePixelRatio来修改meta标签的scale,要注释上面的meta标签
            (function () {
                return
                var dpr = scale = 1
                var isIPhone = win.navigator.appVersion.match(/iphone/gi)
                var devicePixelRatio = win.devicePixelRatio
                if (isIPhone) {
                    // iOS下，对于2和3的屏，用2倍的方案，其余的用1倍方案
                    if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
                        dpr = 3
                    } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)) {
                        dpr = 2
                    } else {
                        dpr = 1
                    }
                } else {
                    // 其他设备下，仍旧使用1倍的方案
                    dpr = 1
                }
                scale = 1 / dpr

                //
                var metaEl = ''
                metaEl = doc.createElement('meta')
                metaEl.setAttribute('name', 'viewport')
                metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no')
                if (docEl.firstElementChild) {
                    docEl.firstElementChild.appendChild(metaEl)
                } else {
                    var wrap = doc.createElement('div')
                    wrap.appendChild(metaEl)
                    doc.write(wrap.innerHTML)
                }
            })()
        })(document, window)
    }
}

function timestampToTime(timestamp, hms = true, getDetail) {
    if (!timestamp) return timestamp;
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear();
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    let D = change(date.getDate());
    let h = change(date.getHours());
    let m = change(date.getMinutes());
    let s = change(date.getSeconds());
    if (getDetail) {
        const detailDate = {
            Y: Y,
            M: M,
            D: D,
        };
        if (hms) {
            detailDate.h = h;
            detailDate.m = m;
            detailDate.s = s;
        }
        return detailDate;
    }
    if (hms) {
        return `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return `${Y}-${M}-${D}`;
}

function timestampTime(timestamp, hms = true, day = true) {
    if (!timestamp) return timestamp;
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear();
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    let D = change(date.getDate());
    let h = change(date.getHours());
    let m = change(date.getMinutes());
    let s = change(date.getSeconds());
    if (!hms && day) {
        return Y + '-' + M + '-' + D;
    }
    if (!day) {
        return Y + '-' + M;
    }
    return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
}

function change(t) {
    if (t < 10) {
        return "0" + t;
    } else {
        return t;
    }
}

// 校验字符串是否为数字
function checkStrIsNum(str) {
    const reg = /^\d+$/g;
    const result = reg.test(str);
    reg.lastIndex = 0;
    return result;
}

function moreTime() {
    let newdate = new Date().getTime()
    let olddate = localStorage.getItem('inspection_time')

    if (newdate - olddate < 18000000) {
        return true
    } else {
        return false
    }
}

function dataToTimestamp(date, type) {
    if (!date || !date.trim()) return '';
    let _date = date.replace(/-/g, '/');
    if (type === 'start' && (_date.indexOf(' 00:00:00') === -1)) {
        _date += ' 00:00:00';
    } else if (type === 'end' && (_date.indexOf(' 23:59:59') === -1)) {
        _date += ' 23:59:59';
    }
    return new Date(_date).getTime();
}

// 计算baseTimestamp为基准的多少天之前（之后）的日期
function getDateTime(dayNum,baseTimestamp) {
    // var dateDay = new Date();
    let baseDay = new Date(timestampToTime(baseTimestamp,false))
    baseDay .setDate(baseDay .getDate() + dayNum) //获取dayNum天后的日期
    // console.log(baseDay );
    let y = baseDay .getFullYear();
    let m = (baseDay .getMonth() + 1) < 10 ? "0" + (baseDay .getMonth() + 1) : (baseDay .getMonth() + 1); //获取当前月份的日期，不足10补0
    let d = baseDay .getDate() < 10 ? "0" + baseDay .getDate() : baseDay .getDate(); //获取当前几号，不足10补0
    return y + "-" + m + "-" + d;
}

// 屏幕尺寸变化监听

function screenResize(cb) {
    let windowWidth = window.innerWidth;
    const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
    window.addEventListener(resizeEvt, () => {
        const newWindowWidth = window.innerWidth;
        if (windowWidth !== newWindowWidth) {
            cb && cb();
            windowWidth = newWindowWidth;
        }
    });
}

// 全局loading显示
function globleLoading() {
    let _loadingConfig = {
        countLoading: 0,
        loading: '',
    };
    return {
        show() {
            if (_loadingConfig.countLoading <= 0) {
                _loadingConfig.loading = Vue.$loading.show({
                    width: 50,
                    height: 50,
                    color: '#2d8cf0',
                    zIndex: 1030,
                });
            }
            _loadingConfig.countLoading += 1;
        },
        // 配合其他判断条件的隐藏，手动_loadingConfig.countLoading -= 1;详细看request.js
        hide() {
            if (_loadingConfig.countLoading <= 0) {
                // Vue.$loading.show();
                // Vue.$loading.hide();
                _loadingConfig.loading && _loadingConfig.loading.hide();
            }
        },
        loadingConfig: _loadingConfig,
        // 自己调用_loadingConfig.countLoading -= 1来隐藏
        selfHide() {
            _loadingConfig.countLoading -= 1;
            this.hide();
        },
    }
}

function getObjDate(date) {
    if (date) return new Date(date);
    return new Date();
}

function getTimestamp(time, type) {
    if (typeof time === 'object') {
        if (type === 'start') {
            time.setHours(0);
            time.setMinutes(0);
            time.setSeconds(0);
        } else if (type === 'end') {
            time.setHours(23);
            time.setMinutes(59);
            time.setSeconds(59);
        }
        return parseInt(time.getTime() / 1000);
    } else if (typeof time === 'number') {
        if ((time + '').length === 13) return parseInt(time / 1000);
        else return time;
    } else return parseInt(dataToTimestamp(time, type) / 1000);
}

function leftTimer(endtime) {
    var endtime = Number(endtime);
    // var starttime = Date.parse(new Date()) / 1000;
    var leftTime = endtime;
    if (leftTime > 0) {
        //计算剩余的毫秒数
        var days = parseInt(leftTime / 60 / 60 / 24, 10); //计算剩余的天数
        var hours = parseInt(leftTime / 60 / 60 % 24, 10); //计算剩余的小时
        var minutes = parseInt(leftTime / 60 % 60, 10);//计算剩余的分钟
        var seconds = parseInt(leftTime % 60, 10);//计算剩余的秒数
        // days = checkTime(days);
        hours = checkTime(hours);
        minutes = checkTime(minutes);
        seconds = checkTime(seconds);
        // document.getElementById("timer").innerHTML = days+"天" + hours+"小时" + minutes+"分"+seconds+"秒";
        // vue.time = days + vue.data.day + hours + ":" + minutes + ":" + seconds;
        var time1 = days;
        var time2 = hours + ":" + minutes + ":" + seconds;
        return `${time1} Day ${time2}`;
    } else {
        var time1 = '0';
        var time2 = '00:00:00';
        return `${time1} Day ${time2}`;
    }
}

function leftTimerMin(endTime) {
    if (!endTime) return 0;
    return checkTime(parseInt(endTime / 60)) + ':' + checkTime(endTime % 60);
}

function checkTime(i) { //将0-9的数字前面加上0，例1变为01
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function numScale(num, m) {
    // 拆分整数、小数部分
    var parts = num.toString().split('.');
    // 原始值的整数位数
    const integerLen = parts[0].length;
    // 原始值的小数位数
    const decimalLen = parts[1] ? parts[1].length : 0;

    // 放大，当放大的倍数比原来的小数位大时，需要在数字后面补零
    if (m > 0) {
        // 补多少个零：m - 原始值的小数位数
        let zeros = m - decimalLen;
        while (zeros > 0) {
            zeros -= 1;
            parts.push(0);
        }
        // 缩小，当缩小的倍数比原来的整数位大时，需要在数字前面补零
    } else {
        // 补多少个零：m - 原始值的整数位数
        let zeros = Math.abs(m) - integerLen;
        while (zeros > 0) {
            zeros -= 1;
            parts.unshift(0);
        }
    }

    // 小数点位置，也是整数的位数:
    //    放大：原始值的整数位数 + 放大的倍数
    //    缩小：原始值的整数位数 - 缩小的倍数
    var index = integerLen + m;
    // 将每一位都拆到数组里，方便插入小数点
    parts = parts.join('').split('');
    // 当为缩小时，因为可能会补零，所以使用原始值的整数位数
    // 计算出的小数点位置可能为负，这个负数应该正好是补零的
    // 个数，所以小数点位置应该为 0
    parts.splice(index > 0 ? index : 0, 0, '.');

    return parseFloat(parts.join(''));
}


//去除左右两边空格
function trim(s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
}

//深拷贝对象
function deepClone(obj) {
    if (obj === null) return null;
    if (typeof obj !== 'object') return obj;
    if (obj instanceof Date) {
        let date = new Date();
        date.setTime(obj.getTime());
        return date;
    }
    if (obj instanceof RegExp) {
        let re = new RegExp(obj.source);
        re.lastIndex = obj.lastIndex;
        return re;
    }
    let newObj = new obj.constructor();
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = deepClone(obj[key]);
        }
    }
    return newObj;
}

//  秒数转化为时分秒
function formatSeconds(value,sec = true) {
    if (parseInt(value) === 0) return '/'
    //  秒
    let second = parseInt(value)
    //  分
    let minute = 0
    //  小时
    let hour = 0
    //  天
    //  let day = 0
    //  如果秒数大于60，将秒数转换成整数
    if (second > 60) {
        //  获取分钟，除以60取整数，得到整数分钟
        minute = parseInt(second / 60)
        //  获取秒数，秒数取佘，得到整数秒数
        second = parseInt(second % 60)
        //  如果分钟大于60，将分钟转换成小时
        if (minute > 60) {
            //  获取小时，获取分钟除以60，得到整数小时
            hour = parseInt(minute / 60)
            //  获取小时后取佘的分，获取分钟除以60取佘的分
            minute = parseInt(minute % 60)
            //  如果小时大于24，将小时转换成天
            //  if (hour > 23) {
            //    //  获取天数，获取小时除以24，得到整天数
            //    day = parseInt(hour / 24)
            //    //  获取天数后取余的小时，获取小时除以24取余的小时
            //    hour = parseInt(hour % 24)
            //  }
        }
    }

    let result = ''
    if (sec){
        result = parseInt(second) + '秒'
    }

    if (minute > 0) {
        result = '' + parseInt(minute) + '分' + result
    }
    if (hour > 0) {
        result = '' + parseInt(hour) + '小时' + result
    }
    return result
}

function weekDay(time) {

    const weekNum = new Date( timestampTime(time)).getDay();
    const week = {
        0: '日',
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六'
    }
    return week[weekNum] ? week[weekNum] : '日期错误';
}
function hsak(path,obj) {
    const props = path.split('.'); // 将路径字符串分割成属性名数组
    return props.reduce((obj, prop) => (obj || {})[prop], obj);
}
function JSONToExcelConvertor(JSONData, FileName, title, filter) {
    if (!JSONData)
        return;
    //转化json为object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

    var excel = "<table>";

    //设置表头
    var row = "<tr>";
    let children  =[]
    if (title) {
        //使用标题项
        title.forEach((item)=>{
            if(item.children&&item.children.length>0){
                row += `<th align='center' colspan='${item.children.length}'>  ${item.title} </th>`;
                children = children.concat(item.children)
            }else {
                row += "<th align='center' >" + item.title + '</th>';
                children.push({title:'',key:item.key})
            }
        })


    } else {
        //不使用标题项
        for (var i in arrData[0]) {
            row += "<th align='center'>" + i + '</th>';
        }
    }

    excel += row + "</tr>";
    if(children.length>0){
        let ro = "<tr>";
        children.forEach((ite)=>{
            ro += "<th align='center' >" + ite.title + '</th>';

        })
        excel += ro + "</tr>";
    }


    // //设置数据
    // for (var i = 0; i < arrData.length; i++) {
    //     var row = "<tr>";
    //
    //     for (var index in arrData[i]) {
    //         //判断是否有过滤行
    //         if (filter) {
    //             if (filter.indexOf(index) == -1) {
    //                 var value = arrData[i][index] == null ? "" : arrData[i][index];
    //                 row += '<td>' + value + '</td>';
    //             }
    //         } else {
    //             var value = arrData[i][index] == null ? "" : arrData[i][index];
    //             row += "<td align='center'>" + value + "</td>";
    //         }
    //     }
    //
    //
    //
    //     excel += row + "</tr>";
    // }

    arrData.forEach((item)=>{
        var row = "<tr>";

        children.forEach((ite)=>{
            row += '<td>' + hsak(ite.key,item) + '</td>';

        })
        excel += row + "</tr>";

    })


    excel += "</table>";

    var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
    excelFile += '; charset=UTF-8">';
    excelFile += "<head>";
    excelFile += "<!--[if gte mso 9]>"
    excelFile += "<xml>";
    excelFile += "<x:ExcelWorkbook>";
    excelFile += "<x:ExcelWorksheets>";
    excelFile += "<x:ExcelWorksheet>";
    excelFile += "<x:Name>";
    excelFile += "{worksheet}";
    excelFile += "</x:Name>";
    excelFile += "<x:WorksheetOptions>";
    excelFile += "<x:DisplayGridlines/>";
    excelFile += "</x:WorksheetOptions>";
    excelFile += "</x:ExcelWorksheet>";
    excelFile += "</x:ExcelWorksheets>";
    excelFile += "</x:ExcelWorkbook>";
    excelFile += "</xml>";
    excelFile += "<![endif]-->";
    excelFile += "</head>";
    excelFile += "<body>";
    excelFile += excel;
    excelFile += "</body>";
    excelFile += "</html>";

    var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);

    var link = document.createElement("a");
    link.href = uri;

    link.style = "visibility:hidden";
    link.download = FileName + ".xls";
    //
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);



}

function downloadForm(table,FileName='今天'){

    var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
    excelFile += '; charset=UTF-8">';
    excelFile += "<head>";
    excelFile += "<!--[if gte mso 9]>"
    excelFile += "<xml>";
    excelFile += "<x:ExcelWorkbook>";
    excelFile += "<x:ExcelWorksheets>";
    excelFile += "<x:ExcelWorksheet>";
    excelFile += "<x:Name>";
    excelFile += "{worksheet}";
    excelFile += "</x:Name>";
    excelFile += "<x:WorksheetOptions>";
    excelFile += "<x:DisplayGridlines/>";
    excelFile += "</x:WorksheetOptions>";
    excelFile += "</x:ExcelWorksheet>";
    excelFile += "</x:ExcelWorksheets>";
    excelFile += "</x:ExcelWorkbook>";
    excelFile += "</xml>";
    excelFile += "<![endif]-->";
    excelFile += "</head>";
    excelFile += "<body>";
    excelFile += table;
    excelFile += "</body>";
    excelFile += "</html>";

    var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);

    var link = document.createElement("a");
    link.href = uri;

    link.style = "visibility:hidden";
    link.download = FileName + ".xls";
    //
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

}


export default {
    inWeiXin: inWeiXin,
    setMeta: setMeta,
    environment: environment,
    adaptive: adaptive,
    websiteAdaptive: websiteAdaptive,
    phoneType: phoneType,
    timestampToTime: timestampToTime,
    timestampTime: timestampTime,
    change,
    checkStrIsNum,
    moreTime,
    dataToTimestamp,
    screenResize,
    globleLoading,
    getObjDate,
    getTimestamp,
    leftTimer,
    checkTime,
    leftTimerMin,
    numScale,
    trim,
    deepClone,
    formatSeconds,
    getDateTime,
    weekDay,
    JSONToExcelConvertor,
    downloadForm

}
